﻿using ColiyerDependencyInject;
using ColiyerDependencyInject.Commom;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ColiyerLogger
{
    /// <summary>
    /// 控制台订阅
    /// </summary>
    public class ConsoleOutputWatcher
    {
        private StringWriter _stringWriter;
        private TextWriter _originalConsoleOut;
        // 事件，当有新的控制台输出时触发
        public event Action<string> OnConsoleOutput;
        /// <summary>
        /// 用于获取Token和取消token的类
        /// </summary>
        private readonly TokenHandler _tokenHandler = new TokenHandler();

        /// <summary>
        /// 开始订阅控制台输出
        /// </summary>
        public void Start()
        {
            return;
            _stringWriter = new StringWriter();
            _originalConsoleOut = Console.Out;

            // 将控制台输出重定向到 StringWriter
            Console.SetOut(_stringWriter);
            CancellationToken token = _tokenHandler.CancelAndCreateNewToken();

            Task.Run(() =>
            {
                while (!token.IsCancellationRequested)
                {
                    // 检查是否有新的控制台输出
                    var output = _stringWriter.ToString();
                    if (!string.IsNullOrEmpty(output))
                    {
                        // 触发事件，传递控制台输出内容
                        OnConsoleOutput?.Invoke(output);

                        // 清空已经读取的内容
                        Clear();
                    }
                    // 等待一小段时间以避免CPU过度占用
                    Thread.Sleep(100);
                }
            }, token);
        }

        /// <summary>
        /// 停止订阅控制台输出并处理捕获的内容
        /// </summary>
        public void Stop()
        {

            if (_stringWriter != null)
            {
                _tokenHandler.Cannel();

                // 恢复原始的控制台输出
                Console.SetOut(_originalConsoleOut);

                // 清理资源
                _stringWriter.Dispose();
                _stringWriter = null;
            }
        }

        /// <summary>
        /// 清空控制台输出捕获的数据
        /// </summary>
        public void Clear()
        {
            _stringWriter?.GetStringBuilder().Clear();
        }
    }
}
